from flask import Blueprint, request, jsonify, make_response, render_template, send_from_directory, url_for, flash, current_app
from fileshare.extensions import db, csrf
from flask_login import login_required, current_user
from fileshare.models import FileShare, Admin
from fileshare.file_utils import b64decode_, getFileSize
from fileshare.utils import redirect_back
import os
import time
import datetime
import json
import traceback


share_bp = Blueprint('share', __name__)


@csrf.exempt
@share_bp.route('/', methods=['GET', 'POST'])
@login_required
def page():
    if request.method == 'GET':
        return render_template("share/share.html")
    response = {'status': False}
    try:
        sqlResult = FileShare.query.filter_by(
            username=current_user.username).all()
        result = []
        for i in sqlResult:
            if i.validdate:
                if int(i.validdate) < int(time.time()):
                    validdate = '已过期'
                else:
                    validdate = datetime.datetime.fromtimestamp(
                        int(i.validdate))
                    # validdate = time.localtime(int(i.validdate))
            else:
                validdate = '永久有效'
            result.append({
                'filename': os.path.split(i.filepath)[1],
                'filepath': i.filepath.replace('\\', '\\\\'),
                'filesize': i.filesize,
                'getcode': i.getcode,
                'code': i.code,
                # 'validdate': datetime.datetime.fromtimestamp(int(i.validdate)).strftime("%Y--%m--%d %H:%M:%S")
                'validdate': validdate,
            })
        response['data'] = result
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)
    response['code'] = 0
    response['msg'] = 'success'
    response['status'] = True
    return jsonify(response)


# 新增文件分享
@csrf.exempt
@ share_bp.route('/create', methods=['POST'])
@ login_required
def create():
    response = {'status': False}
    filepath = request.values.get("filename")
    validdate = request.values.get('validdate')
    getcode = request.values.get('getcode')
    try:
        filepath = b64decode_(filepath)
        # 防止目录参数被串改
        if current_user.get_filenames_all() not in filepath:
            response['code'] = 4000
            response['msg'] = '请勿更改目录'
            return jsonify(response)
        file = FileShare.query.filter_by(
            filepath=filepath, username=current_user.username).first()
        filesize = getFileSize(filepath)
        if file:
            # 存在就更新操作
            file.getcode = getcode
            file.validdate = int(time.time())+int(validdate) * \
                86400 if validdate else ''
        else:
            # 新增分享
            file = FileShare()
            file.getcode = getcode
            file.filepath = filepath
            file.code = file.get_code()
            file.filesize = filesize
            file.validdate = int(time.time())+int(validdate) * \
                86400 if validdate else ''
            file.username = current_user.username
            db.session.add(file)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)
    response['code'] = 0
    response['msg'] = 'success'
    response['status'] = True
    response['data'] = url_for('share.show', code=file.code)
    return jsonify(response)


# 删除文件分享
@csrf.exempt
@ share_bp.route('/delete', methods=['POST'])
@ login_required
def delete():
    response = {'status': False}
    code = request.values.get('code')
    try:
        file = FileShare.query.filter_by(
            code=code, username=current_user.username).first()
        if file:
            db.session.delete(file)
            db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)
    response['code'] = 0
    response['msg'] = 'success'
    response['status'] = True
    return jsonify(response)


# 取消多个文件分享
@csrf.exempt
@ share_bp.route('/deletes', methods=['POST'])
@ login_required
def deletes():
    response = {'status': False}
    try:
        code = json.loads(request.values.get('code'))
        for i in code:
            file = FileShare.query.filter_by(
                code=i, username=current_user.username).first()
            if file:
                db.session.delete(file)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)
    response['code'] = 0
    response['msg'] = 'success'
    response['status'] = True
    return jsonify(response)


# 文件展示页面
@ csrf.exempt
@ share_bp.route('/<code>', methods=['GET'])
def show(code):
    response = {'status': False}
    try:
        result = FileShare.query.filter_by(code=code).first()
        if int(result.validdate) < int(time.time()):
            flash('文件已过期', 'info')
            return redirect_back()
        result = {
            'filename': os.path.split(result.filepath)[1],
            'filepath': result.filepath.replace('\\', '\\\\'),
            'filesize': result.filesize,
            'getcode': result.getcode,
            'code': result.code,
            'validdate': datetime.datetime.fromtimestamp(int(result.validdate)).strftime("%Y--%m--%d %H:%M:%S") if result.validdate else '永久有效',
        }
        return render_template("share/fileshare.html", result=result)
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)


# 下载
@ csrf.exempt
@ share_bp.route('/down', methods=['GET'])
def down():
    response = {'status': False}
    try:
        code = request.values.get('code')
        getcode = request.values.get('getcode', '')
        sqlresult = FileShare.query.filter_by(code=code).first()
        if getcode == sqlresult.getcode:
            if int(sqlresult.validdate) > int(time.time()):
                fileName = sqlresult.filepath
                response = make_response(send_from_directory(os.path.split(fileName)[
                    0], os.path.split(fileName)[1], as_attachment=True, attachment_filename='123'))
                response.headers["Content-Disposition"] = "attachment; filename={}".format(
                    os.path.split(fileName)[1].encode().decode('latin-1'))
                return response
            else:
                flash('文件已过期', 'info')
                return redirect_back()
        else:
            flash('提取码错误！', 'warning')
            return redirect_back()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(traceback.format_exc())
        response['code'] = 4000
        response['msg'] = str(e)
        return jsonify(response)
